#!/bin/bash
# **********************************************************
# * File Name     : prometheus.sh
# * Author        : zzdict
# * Email         : zzdict@gmail.com / elk_deer@foxmail.com
# * Create time   : 2024-08-01 15:12
# * Description   : 在此目录创建脚本/usr/local/bin/prometheus.sh 加上执行权限 使用ln -s创建软连接ln -s /usr/local/bin/prometheus.sh /usr/local/bin/prometheus   使用prometheus start|stop管理
# **********************************************************
# Prometheus 的安装路径
PROMETHEUS_PATH="/opt/prometheus"
PROMETHEUS_BINARY="$PROMETHEUS_PATH/prometheus"
PROMETHEUS_CONFIG="$PROMETHEUS_PATH/prometheus.yml"
PROMETHEUS_PID_FILE="$PROMETHEUS_PATH/prometheus.pid"
 
start() {
    if [ -f "$PROMETHEUS_PID_FILE" ]; then
        echo "Prometheus 已经在运行。"
        return
    fi
    
    echo "启动 Prometheus..."
    nohup "$PROMETHEUS_BINARY" --config.file="$PROMETHEUS_CONFIG" > "$PROMETHEUS_PATH/prometheus.log" 2>&1 &
    echo $! > "$PROMETHEUS_PID_FILE"
    echo "Prometheus 启动成功。"
}
 
stop() {
    if [ ! -f "$PROMETHEUS_PID_FILE" ]; then
        echo "Prometheus 没有运行。"
        return
    fi
    
    echo "停止 Prometheus..."
    PID=$(cat "$PROMETHEUS_PID_FILE")
    kill "$PID"
    rm -f "$PROMETHEUS_PID_FILE"
    echo "Prometheus 停止成功。"
}
 
restart() {
    echo "重启 Prometheus..."
    stop
    start
}
 
status() {
    if [ -f "$PROMETHEUS_PID_FILE" ]; then
        echo "Prometheus 正在运行。"
    else
        echo "Prometheus 没有运行。"
    fi
}
 
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    *)
        echo "用法: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac